package com.hongtu.supplychain.finance.log;

import com.google.gson.Gson;
import com.hongtu.supplychain.finance.util.Constants;
import com.hongtu.supplychain.finance.util.RequestWrapperUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.UUID;

/**
 * Created by Administrator on 2016/9/30.
 */
public class RequestBodyLogger implements Filter {
    private final Logger logger = Logger.getLogger(getClass());
    private static Gson gson = new Gson();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("请求过滤器加载完成");
    }

    @Override
    public void destroy() {
        logger.info("过滤器销毁完成");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;

        if(request instanceof HttpServletRequest) {
            // 非get请求才需要记录请求报文
            if (!((HttpServletRequest) request).getMethod().toLowerCase().equals("get")) {
                RequestWrapperUtil rq = new RequestWrapperUtil((HttpServletRequest) request);
                requestWrapper = rq;
                //保存请求报文
                saveRequestMessage((HttpServletRequest) requestWrapper, rq.getBody());
            }
        }
        if(null == requestWrapper) {
            filterChain.doFilter(request, response);
        } else {
            filterChain.doFilter(requestWrapper, response);
        }
    }

    /**
     * 打印请求报文详情
     * @param request
     * @param paramsJson
     */
    private void saveRequestMessage(HttpServletRequest request, String paramsJson) {
        String method = request.getMethod();
        String reqId = UUID.randomUUID().toString();
        request.setAttribute(Constants.REQUEST_OR_RESPONSE_ID, reqId);
        logger.error("requestID: " + reqId + "  request address: [" + getFullUrl(request)  +
                "], request method: [" + method.toUpperCase() +
                "], request accept: [" + request.getHeader("accept") +
                "], request charset: [" + request.getHeader("accept-encoding") +
                "], json params: " + (!StringUtils.isEmpty(paramsJson) ? paramsJson.replaceAll("\\s{2,}|\t|\r|\n", "") : "{}") + "," +
                "form data params: "+ gson.toJson(request.getParameterMap()) +
                ", headerNames: [" + headers(request) +"]");
    }

    /**
     * 获取请求地址全路径，包括get请求参数
     * @param request
     * @return
     */
    private String getFullUrl(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder(request.getRequestURL());
        if (request.getQueryString() != null) {
            sb.append('?');
            sb.append(request.getQueryString());
        }
        return sb.toString();
    }

    /**
     * 获取header中的所有key
     * @param request
     * @return
     */
    private String headers(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        Enumeration<String> list = request.getHeaderNames();
        while (list.hasMoreElements()) {
            sb.append(list.nextElement() + ",");
        }
        return sb.toString();
    }
}
